package com.newgoldcurrency.activities.main;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.activities.DeleteAccountActivity;
import com.newgoldcurrency.activities.InputNameActivity;
import com.newgoldcurrency.activities.LoginActivity;
import com.newgoldcurrency.activities.NameActivity;
import com.newgoldcurrency.activities.emailverifyandmodify.EmailVerifyAndModifyActivity;
import com.newgoldcurrency.databinding.FragmentProfileBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ProfileFragment extends Fragment {
    private MainActivity activity;
    private FragmentProfileBinding binding;
    private final List<Call> calls=new ArrayList<>();
    private ActivityResultLauncher<Intent> launcher;
    private boolean has=false;
    private String data;

    @SuppressLint({"SetTextI18n"})
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (MainActivity) getActivity();
        binding = FragmentProfileBinding.inflate(inflater, container, false);
        binding.profileInviteCode.setText(getString(R.string.invitation_code_to_share,App.userBean.invitation_code));
        binding.inviteCodeCopy.setOnClickListener(view -> {
            ClipboardManager cm = (ClipboardManager)activity.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("Label", binding.profileInviteCode.getText().toString());
            cm.setPrimaryClip(mClipData);
            Tools.toast("invitation code is copied");
        });
        binding.profileAccountVerifyButton.setOnClickListener(view -> startActivity(new Intent(activity, EmailVerifyAndModifyActivity.class)));
        binding.profileNameButton.setOnClickListener(view -> {
            if (has){
                launcher.launch(new Intent(activity, NameActivity.class).putExtra("data",data));
            }else{
                launcher.launch(new Intent(activity, InputNameActivity.class));
            }
        });
        binding.profileMail.setText(App.userBean.mail);
        binding.profileDeleteAccount.setOnClickListener(view -> launcher.launch(new Intent(activity, DeleteAccountActivity.class)));
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==3){
                refresh();
            }
            if (result.getResultCode()==4){
                SharedPreferences.Editor edit = App.sp.edit();
                edit.putString("token","");
                edit.apply();
                launcher.launch(new Intent(activity, LoginActivity.class));
                activity.finish();
            }
        });
        checkVerify();
        refresh();
        return binding.getRoot();
    }
    private void checkVerify() {
        if (App.sql.getMailVerify(App.userBean.mail, null)) {
            binding.profileVerification.setVisibility(View.INVISIBLE);
            binding.profileVerification.setText("");
            binding.profileVerified.setVisibility(View.VISIBLE);
            binding.profileAccountVerifyButton.setEnabled(false);
        } else {
            binding.profileVerification.setText(getString(R.string.verification));
            binding.profileVerified.setVisibility(View.INVISIBLE);
            binding.profileVerification.setVisibility(View.VISIBLE);
            binding.profileAccountVerifyButton.setEnabled(true);
        }
    }
    private void refresh() {
        HashMap<String, String> map=new HashMap<>();
        map.put("userId",App.userBean.id);
        Network.post(map, "user/getAccountAuthentication", call -> {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    activity.runOnUiThread(() -> {
                        try {
                            JsonObject jo = JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject();
                            if (jo.has("data")){
                                has=true;
                                data= jo.get("data").toString();
                            }else {
                                has=false;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    });
                }
            });
            calls.add(call);
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        for (Call c :calls) c.cancel();
        binding = null;
    }
}